const koa = require('koa')
const Router = require('koa-router')
const mongoose = require('mongoose')
const bodyparser = require('koa-bodyparser')
const passport = require('koa-passport')

// 实例化
const app = new koa()
const router = new Router()

app.use(bodyparser())

// 引入
const users = require('./routes/api/users')

// 路由
router.get('/', async ctx => {
  ctx.body = {
    msg: 'hello koa !'
  }
})

// 连接数据库
const db = require('./config/keys').mongoURI

mongoose
  .connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log('数据库连接成功')
  })
  .catch(() => {
    console.log(err)
  })

app.use(passport.initialize())
app.use(passport.session())

//
require('./config/passport')(passport)

// 配置路由地址
router.use('/api/users', users)

// 配置路由
app.use(router.routes()).use(router.allowedMethods())

const port = process.env.PROT || 5000

app.listen(port, () => {
  console.log(`服务器启动成功，端口号：${port}`)
})
